import { _decorator, Component, director, game, Label, Node, ProgressBar, sys } from 'cc';
import { GlobalVar } from './GlobalVar';
import { HttpCom } from './net/HttpCom';
import { Config } from './Config';
const { ccclass, property } = _decorator;
import CryptoJS from 'crypto-js';
import { GameEvent } from './EventName';
@ccclass('Loading')
export class Loading extends Component {

    @property(ProgressBar)
    bar: ProgressBar = null;
    @property(Label)
    versionLab: Label = null;

    

    tgInitData: string = "";

    inviteCode: string = "";

    clickCount: number = 0;
    start() {
        this.versionLab.string = Config.version;
    director.preloadScene('game',(completedCount, totalCount, item)=>{
            var progress = completedCount / totalCount;
            //console.log(progress)
            this.bar.progress = progress;
        },
        ()=>{
            this.initData();
        }
    )

    
    //director.loadScene('game');
}
showBuildVersion(){
    //game.emit(GameEvent.SHOW_TOAST,Config.buildVersion);
    this.clickCount ++;
    if(this.clickCount > 5){
        this.versionLab.string = Config.buildVersion;
    }
}

 safeParse(start_param) {
    try {
      const str = atob(start_param);
      return JSON.parse(str);
    } catch (error) {
      return {};
    }
  }
//   useLayoutEffect(() => {
//       if (webApp?.initDataUnsafe.start_param) {
//         const { type, projectUrl, campaignId } = safeParse(
//           webApp?.initDataUnsafe.start_param
//         );
//         if (type === 'campaign') {
//           navigate(`/${projectUrl}/${campaignId}`);
//         }
//       }
//   }, []);

test(){
    let v =  btoa(
        JSON.stringify({ inviteCode: "8X7USO"}))

    let o = this.safeParse(v)

    console.log(o,"oooo")
}

    initData(){
        if(window['Telegram']){

            //const telegram = window['Telegram'].WebApp.initData
            
        }
        const url = window.location.href;
        console.log(url,"网页地址")
        const url1 = new URL(url);
        const inviteCode = url1.searchParams.get("inviteCode")
        this.inviteCode = inviteCode;
        console.log(this.inviteCode,"URL邀请码")
        this.processInitData();

        //let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJhcGlfdXNlcjoxMDAwMTEiLCJyblN0ciI6IlBNU2N1R2J5QzJVWGxyRjM2RjZpODVSMVhkWDRVdlR0IiwiYXBpVXNlcklkIjoxMDAwMTF9.GjZ8QjoeuVi6QBLQ-Q5Z4TQyAhyph-ga_HzK-inbYZU";
        
        
        //this.getUserInfo();
    }

    userLogin(){
        this.getUserInfo();
    }

    loadTelegramSDK() {

        // this.url.string = 'loadTelegramSDK'
        
        return new Promise<void>((resolve, reject) => {
        
        if (window['Telegram'] && window['Telegram'].WebApp) {
        
        // Telegram SDK 已经加载
        
        console.log('Telegram SDK 已经加载:', window['Telegram']);
        
        window['Telegram'].WebApp.ready();
        
        resolve();
        
        return;
        
        }
        
        const script = document.createElement('script');
        
        script.src = 'https://telegram.org/js/telegram-web-app.js';
        
        script.onload = () => {
        
        console.log('SDK 加载成功:', window['Telegram']);
        
        window['Telegram'].WebApp.ready();
        
        // SDK 加载成功
        
        resolve();
        
        };
        
        script.onerror = error => {
        
        console.log('SDK 加载失败:', error);
        
        // SDK 加载失败
        
        reject(error);
        
        };
        
        document.head.appendChild(script);
        
        });
        
        }
        
    processInitData() {
    const user = window['Telegram'].WebApp.initData;
    const initDataUnsafe = window['Telegram'].WebApp.initDataUnsafe;
    console.log('initData:', user);
    console.log('initDataUnsafe:', initDataUnsafe);
    const initData = window['Telegram']?.WebApp?.initData;
    if (initData) {
    const searchParams = new URLSearchParams(initData);
    const WebAppData = {};
    for (const [key, value] of searchParams.entries()) {
    WebAppData[key] = value;
    }
    console.log('WebAppData:', WebAppData);
    // 获取用户信息
    //const user = window['Telegram'].WebApp.initDataUnsafe;
    const user = window['Telegram'].WebApp.initData;
    const initDataUnsafe = window['Telegram'].WebApp.initDataUnsafe;
    console.log('initData:', user);
    console.log('initDataUnsafe:', initDataUnsafe);

    let  CodeJson = this.safeParse(initDataUnsafe.start_param);
    console.log(CodeJson,"codeJson");
    this.inviteCode = CodeJson.inviteCode;
    console.log(this.inviteCode,"邀请码");
    HttpCom.tgLogin(user,this.inviteCode,(resp)=>{
        let token = resp.data.token;
        GlobalVar.token = token;
        this.getUserInfo();
    })
    // this.WebAppData = WebAppData;
    // 处理窗口大小变化
    window['Telegram'].WebApp.onEvent('resize', function () {
    // 更新 UI
    console.log('更新 UI:');
    });
    this.tgInitData = initData;
    } else {
    console.warn('Telegram WebApp initData is not available.');
    let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJhcGlfdXNlcjoxMDAwMTEiLCJyblN0ciI6IlBNU2N1R2J5QzJVWGxyRjM2RjZpODVSMVhkWDRVdlR0IiwiYXBpVXNlcklkIjoxMDAwMTF9.GjZ8QjoeuVi6QBLQ-Q5Z4TQyAhyph-ga_HzK-inbYZU";
    let initData = ""
    let localData = sys.localStorage.getItem("XstarInitData")
    if(localData){
        initData = localData;
    }else{
        initData = "user=%7B%22id%22%3A6907868341%2C%22first_name%22%3A%22he%22%2C%22last_name%22%3A%22%22%2C%22username%22%3A%22tobenumber01%22%2C%22language_code%22%3A%22en%22%2C%22allows_write_to_pm%22%3Atrue%7D&chat_instance=-7210699924162316522&chat_type=private&start_param=eyJpbnZpdGVDb2RlIjoiR1VDTDJXIn0%3D&auth_date=1727186626&hash=9c9c951c8ff799df86e69ed1c430dabdca0d618e6fd0191eaaa29bf7ef72952a"
    }
    HttpCom.tgLogin(initData,this.inviteCode,(resp)=>{
        let token = resp.data.token;
        GlobalVar.token = token;
        this.getUserInfo();
    })
    
    

}
    
    }
        
    async initTelegram() {
    
    try {
    
    await this.loadTelegramSDK();
    
    this.processInitData();
    
    } catch (error) {
    
    console.error('Failed to load Telegram SDK:', error);
    
    }
    
    }


    getUserInfo(){
        //return;
        HttpCom.get(Config.getInfo,(resp)=>{
            console.log(resp,"用户信息")

            GlobalVar.userInfo = resp.data.user;
            director.loadScene('game');

            console.log(GlobalVar.userInfo,"用户信息");
        })
    }

    update(deltaTime: number) {
        
    }

    //sign 签名算法
    
    formatParams(params){
        Object.keys(params).map(key => {
            switch(params[key]){
                case undefined:
                    case null:
                        params[key] =  '';
                    }
                });
                
                return params;
    }
            
    generateSignature(params){
    var secretKey = "KriSL1SOeinZ1RNCixjtPw==";
    const sortParams = Object.keys(params).sort();
    const sortParamsString = sortParams.map( key =>`${key}=${params[key]}`).join('&');
    return CryptoJS.HmacSHA256(sortParamsString, secretKey).toString();
    }

    login(){
        let rawData = 'query_id=AAGM98MpAwAAAIz3wymNLzlx&user=%7B%22id%22%3A7143159692%2C%22first_name%22%3A%22gugu%22%2C%22last_name%22%3A%22guoer%22%2C%22username%22%3A%22guguwoshiguoer%22%2C%22language_code%22%3A%22zh-hans%22%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1725533277&hash=9f8393cced14a0657d8d84bbd21c7b223932e4087940235c4d82b27f7afc1099'
        HttpCom.post('https://mc-api.liqul.xyz/api/auth/login',{sign: this.generateSignature({tgRawData:rawData,id:1}),tgRawData: rawData,id: 1},(resp)=>{
            console.log(resp,"登录返回")
        })
    }
}


